package com.ray.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.naming.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ray.bean.PermissionBean;
import com.ray.pojo.MyUser;
import com.ray.service.PermissionService;
import com.ray.util.AllPermissionUtil;
import com.ray.util.CookieUtils;
import com.ray.util.ResponseUtil;
import com.ray.util.StringUtil;
import com.ray.util.redis.RedisCache;


public class LoginFilter implements Filter {
	
	@Autowired
	PermissionService permissionService;
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain filterchain) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) arg0;
		HttpServletResponse response=(HttpServletResponse) arg1;
		/**
		 * 哪个页面失去session就在当前页面登陆后跳回这个页面
		 */
		String requestURI = request.getRequestURI().toString();
		String queryString = request.getQueryString();  
		String redirectUrlForLogin = requestURI;
		if(queryString!=null)redirectUrlForLogin=requestURI+"?"+queryString;
		
//		String path=request.getRequestURI();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		HttpSession session=request.getSession(true);
		try {
			StringUtil.setRequestUrl(arg0, filterchain, arg1);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		String path=request.getServletPath();
		String contextPath= request.getContextPath();
		if("".equals(contextPath)) {
			response.sendRedirect("weixin/index.html");
			return ;
		}
		MyUser user=(MyUser)request.getSession().getAttribute("userLogin");
		/**
		 * autoLogin 自动登陆
		 */
		String autoLoginKey = CookieUtils.getCookieValue(request, "autoLogin");
		if(user==null&&autoLoginKey!=null&&!"".equals(autoLoginKey)) {
			MyUser autoLoginUser = (MyUser) RedisCache.getDataFromRedis(autoLoginKey);
			if(autoLoginUser!=null)user=autoLoginUser;
			request.getSession().setAttribute("userLogin",user);
		}
		//如果是访问inde.html  刷新权限
		if(user!=null && (path.endsWith("index.html") || path.endsWith("/"))) {
			if(permissionService == null ) {
				WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); 
				permissionService = (PermissionService) factory.getBean("permissionService"); 
			}
			user.setPermissionList(permissionService.getUserPermissionBeanByUserId(user.getUserId()));
			request.getSession().setAttribute("userLogin",user);
		}
		if(path.endsWith("index.html")||path.endsWith("/")) {
			if("/shoppingMallMgr/releasedMaterial/index.html".equals(path)) {
				filterchain.doFilter(request, response);
			}else if(null==user) {
				checkHtmlIsDatavForLogin(request, response, contextPath, path, redirectUrlForLogin);
				return;
			}
		}
		
		//过滤器注入service空指针异常，需从springBean中获取
		ServletContext sc = request.getSession().getServletContext();
        XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
        
        if(cxt != null && cxt.getBean("permissionService") != null && permissionService == null)
        	permissionService = (PermissionService) cxt.getBean("permissionService");
		
//		PermissionBean permission=permissionService.getPermissionByUrl(path);
		if(path.startsWith("/phoneApp")) {
			int index = path.indexOf("/phoneApp/static");
			if (index > -1) {
				path = path.substring(index);
				request.getRequestDispatcher(path).forward(request, response);
				return;
			}
			request.getRequestDispatcher("/phoneApp/index.html").forward(request, response);
			return;
		}
		
		//不需要权限则放行
		boolean bool=false;
		for(int i=0;i<AllPermissionUtil.All_PERMISSION_ARRAY.length;i++) {
			if(path.equals(AllPermissionUtil.All_PERMISSION_ARRAY[i])) {
				bool=true;
				break;
			}
		}
		//不需要权限   放行
		if(!bool) {
			//filterchain.doFilter(request, response);
			gzipJson(request, response, filterchain);
			return;
		}
//		if(null==permission) {
//			filterchain.doFilter(request, response);
//			return;
//		}
		//没有登录重定向到登录界面
		
		if(null==user) {
			checkHtmlIsDatavForLogin(request, response, contextPath, path, redirectUrlForLogin);
			return;
		}
		
		//获取用户权限
		List<PermissionBean> permissionList=user.getPermissionList();
		if(permissionList==null || permissionList.size()<=0) {
			permissionList=permissionService.getUserPermissionBeanByUserId(user.getUserId());
		}
		for(PermissionBean per:permissionList) {
			if(per.getUrl().equals(path)) {
				 //filterchain.doFilter(request, response);
				 gzipJson(request, response, filterchain);
				 return;  
			}
		}
	
	    if(path.endsWith(".html")||path.endsWith(".jsp")) {
	    	request.getRequestDispatcher("/WEB-INF/view/message.jsp").forward(  
	                request, response);  
	    	return;
	    }
	    
	    ObjectMapper mapper = new ObjectMapper();
	    Map map =new HashMap();
	    map.put(ResponseUtil.RESULT_KEY, ResponseUtil.ERROE);//设置result为false
	    map.put(ResponseUtil.ERROR_INFO_KEY, "没有权限");
	    String json=mapper.writeValueAsString(map);
	    ResponseUtil.ResponseData(response,json);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
	
	public void gzipJson(HttpServletRequest request,HttpServletResponse response,FilterChain filterchain) throws IOException, ServletException {
		String accept = request.getHeader(HttpHeaders.ACCEPT);
		if (accept != null) 
		{
			//如果是json请求格式 或则ajax请求
		 	if (accept.indexOf("application/json") >= 0) 
			{
		 		 System.out.println("Processing GZIPFilter");
                 GZIPResponseWrapper gzipResponse = new GZIPResponseWrapper(response);
                 filterchain.doFilter(request, gzipResponse);
				 gzipResponse.finish();
				 return; 
			}
         }
		filterchain.doFilter(request, response);
	}
	
	//看板页面
	static List<String> datavList =  Arrays.asList(
		"/displayView/queryCapacity.html",//产能看板
		"/attendanceMgr/attendanceBoard/index.html",//考勤看板
		"/remoteEquipment/board/equipmentBoard.html",//设备看板
		"/remoteEquipment/board/wastageBoard.html",//能耗看板
		"/remoteEquipment/board/postSaleBoard.html",//售后看板
		"/remoteEquipment/board/warehouseBoard.html",//仓库看板
		"/remoteEquipment/board/purchaseBoard.html",//采购看板
		"/remoteEquipment/board/financeBoard.html",//财务看板
		"/remoteEquipment/board/qcReportBoard.html"//质检看板
	);
	
	/**
	 * 校验访问的地址是否是看板的
	 */
	public void checkHtmlIsDatavForLogin(HttpServletRequest request,HttpServletResponse response,String contextPath, String path,String redirectUrlForLogin) {
		
		try {
			if(datavList.contains(path)) {//代表是看板
				//给datav设置cookie
				CookieUtils.setCookie(request, response, "datav", redirectUrlForLogin,60*60*24*365*10);
				//跳转到datav登录
				response.sendRedirect(contextPath+"/displayView/login.html?redirectUrlForLogin="+redirectUrlForLogin);
			}else {
				response.sendRedirect(contextPath+"/login.html?redirectUrlForLogin="+redirectUrlForLogin);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
